/*
 * Copyright (c) 2011-2023, ThinkWide (cnet2001@163.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.thinkwide.data.ormapping.conditions;


import com.thinkwide.data.exceptions.MFDataException;
import com.thinkwide.data.util.ArrayUtils;
import com.thinkwide.data.ormapping.conditions.fragment.MFColumnFragment;
import com.thinkwide.data.ormapping.conditions.fragment.MFWhereFragment;
import com.thinkwide.data.ormapping.sql.MFSqlBase;
import com.thinkwide.data.ormapping.sql.MFSqlKeyword;

import java.lang.invoke.SerializedLambda;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Locale;

import static java.util.stream.Collectors.joining;

/**
 * AbstractLambdaWrapper
 *
 * @author andyzhang
 * @since 2023/06/15
 */
public abstract class AbstractLambdaWrapper<T, Children extends AbstractLambdaWrapper<T,  Children>>
        extends AbstractWrapper<T, MFunction<T, ?>, Children>{

    private LinkedHashMap<String,Object> paramNameValuePairs = new LinkedHashMap();

    @SafeVarargs
    @Override
    public final Children select(MFunction<T, ?>... columns) {
        if (ArrayUtils.isNotEmpty(columns)) {
            for(MFunction<T, ?> column:columns){
                this.getSqlFragments().getColumnList().add(new MFColumnFragment(columnsToString(column)));
            }
        }
        return self;
    }
    @Override
    protected String columnsToString(MFunction<T, ?>... columns) {
        return columnsToString(true, columns);
    }

    @SuppressWarnings("unchecked")
    protected String columnsToString(boolean onlyColumn, MFunction<T, ?>... columns) {
        return Arrays.stream(columns).map(i -> columnToString(i, onlyColumn)).collect(joining(MFSqlBase.COMMA));
    }

    @Override
    protected String columnToString(MFunction<T, ?> column) {
        return columnToString(column, true);
    }

    protected String columnToString(MFunction<T, ?> column, boolean onlyColumn) {
        SerializedLambda lambda=extract(column);
        String name = methodToProperty(lambda.getImplMethodName());
        return name;
    }

    public static String methodToProperty(String name) {
        if (name.startsWith("is")) {
            name = name.substring(2);
        } else if (name.startsWith("get") || name.startsWith("set")) {
            name = name.substring(3);
        } else {
            throw new MFDataException("Error parsing property name '" + name + "'.  Didn't start with 'is', 'get' or 'set'.");
        }

        if (name.length() == 1 || (name.length() > 1 && !Character.isUpperCase(name.charAt(1)))) {
            name = name.substring(0, 1).toLowerCase(Locale.ENGLISH) + name.substring(1);
        }

        return name;
    }

    public static <T> SerializedLambda extract(MFunction<T, ?> func) {
        try {
            Method method = func.getClass().getDeclaredMethod("writeReplace");
            return (SerializedLambda) AccessController.doPrivileged(new SetAccessibleAction<>(method)).invoke(func);
        } catch (NoSuchMethodException e) {
            throw new MFDataException(e.getMessage());
        } catch (InvocationTargetException | IllegalAccessException e) {
            throw new MFDataException(e.getMessage());
        }
    }

    protected AbstractLambdaWrapper addCondition(boolean condition, MFunction<T, ?> column, MFSqlKeyword sqlKeyword, Object val) {
        if (condition){
            this.getSqlFragments().getWhereList().add(new MFWhereFragment(columnsToString(column),sqlKeyword.getValue(),val));
        }
        return self;
    }


}
